package com.kfit.demo.controller;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/hello")
public class HelloController {

	@GetMapping
	public String hello() {
		return "hello,Spring Security ，2018年-10年";
	}
	
	
	@GetMapping("/helloAdmin")
	//@PreAuthorize("hasAnyRole('admin')")
	public String helloAdmin() {
		return "hello,admin";
	}
	
	
	@GetMapping("/helloUser")
	//@PreAuthorize("hasAnyRole('normal','admin')")
	@Secured("hasAnyRole('ROLE_normal','ROLE_admin')")//项目中使用很少。ROLE_
	public String helloUser() {
		return "hello,user";
	}
	
	@GetMapping("/helloUser1")
	@PostAuthorize("returnObject!=null &&  returnObject.username == authentication.name")
	public User helloUser1() {
		Object pricipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		User user;
		if("anonymousUser".equals(pricipal)) {
			user = null;
		}else {
			user = (User) pricipal;
		}
		return user;
	}

	
}
